package org.sn.jdish.spark.streaming;

import java.util.regex.Pattern;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import com.google.common.collect.Lists;

import scala.Tuple2;

/**
 * 自定义HDFS-Spark-Streaming-WordCount
 * 
 * @author snzigod@hotmail.com
 */
public final class JavaHDFSWordCount {
	private static final Pattern SPACE = Pattern.compile(" ");

	public static void main(String[] args) {
		SparkConf sparkConf = new SparkConf().setAppName("sparkStreaming").setMaster("local[5]");
		/*
		 * 创建该对象类似于spark core中的JavaSparkContext
		 * 该对象除了接受SparkConf对象，还接收了一个BatchInterval参数,就算说， 没收集多长时间去划分一个人Batch即RDD去执行
		 */
		JavaStreamingContext sc = new JavaStreamingContext(sparkConf, Durations.seconds(5));

		readJson(sc);

		sc.start();
		sc.awaitTermination();

		sc.stop();
		sc.close();
	}

	static void readJson(JavaStreamingContext sc) {
		/*
		 * 首先创建输入DStream，代表一个数据比如这里从socket或KafKa来持续不断的进入实时数据流
		 * 创建一个监听Socket数据量，RDD里面的每一个元素就是一行行的文本
		 */
		JavaDStream<String> lines = sc.textFileStream("hdfs://master:8020/wordcount_dir");

		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Iterable<String> call(String x) {
				return Lists.newArrayList(SPACE.split(x));
			}
		});
		JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Tuple2<String, Integer> call(String s) {
				return new Tuple2<String, Integer>(s, 1);
			}
		}).reduceByKey(new Function2<Integer, Integer, Integer>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Integer call(Integer i1, Integer i2) {
				return i1 + i2;
			}
		});

		wordCounts.print();
	}
}
